﻿package {
	import flash.net.*;
    import flash.media.Sound;;
    import flash.net.URLRequest;
    import flash.media.SoundChannel;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
	import flash.display.MovieClip;
	import flash.events.*;
	public class Player extends MovieClip{
		
		private var playlist:Array;
		private var trackNumber:int;
		private var pl:Playlist; //objekt der styrer XML filen
		
		private var infotext:TextField;
		private var playSlider:PlaySlider;
		
		private var playPos:int;
		private var playLenght:int;
		private var playStatus:Boolean;
		
		private var snd:Sound;
		private var channel:SoundChannel;
	
		public function Player(pl:Playlist,tf:TextField = null){
			this.pl = pl;
			pl.setPlayer(this);
			trackNumber = 0;

			channel = new SoundChannel();
			if(tf != null)
				infotext = tf;
			else{
				infotext = new TextField();
				infotext.autoSize = TextFieldAutoSize.LEFT;
				infotext.text = "Please press to play";
				infotext.x = 50;
				infotext.y = 50;
			}
			this.addChild(infotext);


		}
		
		public function playMusic():void{
			channel.stop();
			playlist = pl.playlist();
			var playSource:URLRequest = new URLRequest(pl.getFilePath(playlist[trackNumber]));
			snd = new Sound(playSource);
			channel = snd.play();
			snd.addEventListener(IOErrorEvent.IO_ERROR,function(ev:IOErrorEvent):void{trace("ERRORERROR");});
			snd.addEventListener(Event.COMPLETE,function(ev:Event):void
										{
											infotext.text = "Trying to play: " + playlist[trackNumber] + ", at file path: " + pl.getFilePath(playlist[trackNumber]);
											playSlider = new PlaySlider(150,150,100);
											addChild(playSlider);
											trace("[snd.lenght:" + snd.length + "]");
											playSlider.startSlider(snd.length);
										});
			channel.addEventListener(Event.SOUND_COMPLETE, function(ev:Event):void 
										{
											nextTrack();
										});
		}
		
		public function nextTrack():void{
			trace("next was pressed");
			if(trackNumber < playlist.length -1)
				trackNumber++;
			else
				trackNumber = 0;
			playMusic();
		}
		
		public function previousTrack():void{
						trace("[snd.lenght:" + snd.length + "]");
			if(trackNumber == 0)
				trackNumber = 0;
			else
				trackNumber -= 1;
			playMusic();
		}
		
		public function getTrackInfo(){
			
		}
		

	}	
}